package com.xdk.templatescala.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * @param minute
     * @return {@link Date}
     */
    public static Date toMinute(String minute){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        try {
            return simpleDateFormat.parse(minute);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 分钟
     *
     * @param date 日期
     * @return {@link String}
     */
    public static String toMinute(Date date){
        return DateFormatUtils.format(date, "HH:mm");
    }


    /**
     * 日期累加
     *
     * @param date 日期
     * @param span 跨度
     * @param time 时间
     * @return {@link String}
     */
    public static String formatMinute(String date, int span, int time){
        Date formatDate = toMinute(date);
        //开始时间
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(formatDate);
        calBegin.add(Calendar.MINUTE, span * time);
        return toMinute(calBegin.getTime());
    }
    /**
     * 计算时间跨度
     *
     * @param duration 持续时间
     * @param times    次
     * @return int
     */
    public static int spanNum(int duration, int times){
        if (StringUtils.isNull(duration)){
            return 1;
        }
        int divisor = duration / times;
        int remainder = duration % times;
        if (remainder > 0){
            return divisor + 1;
        }
        return divisor;
    }


    /**
     * 计算当前日期往前或往后的日期
     *
     * @param day 往前或往后的天数
     * @return {@link String}
     */
    public static String computeDate(int day){
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);
        return parseDateToStr(YYYY_MM_DD, calendar.getTime());
    }

    /**
     * 计算时间
     *
     * @param day 一天
     * @return {@link Date}
     */
    public static Date computeTime(Date date, int day){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);
        return calendar.getTime();
    }

    /**
     * 格式化为当天时间
     *
     * @param date 日期
     * @return {@link Date}
     */
    public static Date computeTime(Date date){
        Calendar oldCalendar = Calendar.getInstance();
        oldCalendar.setTime(date);
        Date nowDate = new Date();
        Calendar nowCalendar = Calendar.getInstance();
        nowCalendar.setTime(nowDate);
        Calendar calendar = Calendar.getInstance();
        calendar.set(nowCalendar.get(Calendar.YEAR), nowCalendar.get(Calendar.MONTH), nowCalendar.get(Calendar.DATE),
                oldCalendar.get(Calendar.HOUR_OF_DAY), oldCalendar.get(Calendar.MINUTE), oldCalendar.get(Calendar.SECOND));
        return calendar.getTime();
    }

    /**
     * diff日期
     * 计算日期相差天数
     *
     * @param beginDate 开始日期
     * @param endDate   结束日期
     * @return long
     */
    public static long diffDate(Date beginDate, Date endDate){
        Calendar beginCalendar = Calendar.getInstance();
        beginCalendar.setTime(beginDate);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);
        long years = endCalendar.get(Calendar.YEAR) - beginCalendar.get(Calendar.YEAR);
        long days = endCalendar.get(Calendar.DAY_OF_YEAR) - beginCalendar.get(Calendar.DAY_OF_YEAR);
        if (years > 0){
            return (years * 365) + days;
        }
        return days;
    }

    /**
     * 计算相差月
     *
     * @param beginDate 开始日期
     * @param endDate   结束日期
     * @return long
     */
    public static long diffMonth(Date beginDate, Date endDate){
        Calendar beginCalendar = Calendar.getInstance();
        beginCalendar.setTime(beginDate);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);
        long month = endCalendar.get(Calendar.MONTH) - beginCalendar.get(Calendar.MINUTE);
        return month;
    }

    /**
     * 计算时间相差分钟数
     *
     * @param beginDate 开始日期
     * @param endDate   结束日期
     * @return long
     */
    public static long diffDateOfMinute(Date beginDate, Date endDate){
        if (StringUtils.isNull(beginDate) || StringUtils.isNull(endDate)){
            return -1;
        }
        Calendar beginCalendar = Calendar.getInstance();
        beginCalendar.setTime(beginDate);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);
        long years = endCalendar.get(Calendar.YEAR) - beginCalendar.get(Calendar.YEAR);
        long days = endCalendar.get(Calendar.DAY_OF_YEAR) - beginCalendar.get(Calendar.DAY_OF_YEAR);
        long hours = endCalendar.get(Calendar.HOUR_OF_DAY) - beginCalendar.get(Calendar.HOUR_OF_DAY);
        long minutes = endCalendar.get(Calendar.MINUTE) - beginCalendar.get(Calendar.MINUTE);
        if (years > 0){
            days = (years * 365) + days;
        }
        return (days * 24 * 60) + (hours * 60) + minutes;
    }

    /**
     * 检查日期
     * 1=周日,2=周一，3=周二，4=周三，5=周四，6=周五，7=周日
     * @param date 日期
     * @return int
     */
    public static int checkWeek(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        return week;
    }

    /**
     * 检查时间重叠
     * 判断两个时间段是否重叠
     *
     * @param aStartTime 一个开始时间
     * @param aEndTime   一个结束时间
     * @param bStartTime b开始时间
     * @param bEndTime   b结束时间
     * @param isStrict   isStrict 是否严格重叠，true 严格，没有任何相交或相等；false 不严格，可以首尾相等，比如2021/5/29-2021/5/31和2021/5/31-2021/6/1，不重叠。
     * @return boolean
     */
    public static boolean checkTimeOverlap(long aStartTime, long aEndTime, long bStartTime, long bEndTime, boolean isStrict){
        if (isStrict){
            if (!(aEndTime < bStartTime || aStartTime > bEndTime)){
                return true;
            }
        } else {
            if (!(aEndTime <= bStartTime || aStartTime >= bEndTime)){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
//        System.out.println(arrangeDate(toMinute("08:00"), toMinute("12:00"), 30));
//        System.out.println(spanNum(70, 30));
//        System.out.println(formatMinute("16:00", 2, 30));
//        System.out.println(diffDateOfMinute(null, dateTime(YYYY_MM_DD_HH_MM_SS, "2024-01-01 15:50:00")));
//        long aStartTime = dateTime(YYYY_MM_DD_HH_MM_SS, "2023-03-22 14:50:00").getTime();
//        long aEndTime = dateTime(YYYY_MM_DD_HH_MM_SS, "2023-03-22 15:40:00").getTime();
//        long bStartTime = dateTime(YYYY_MM_DD_HH_MM_SS, "2023-03-22 15:30:00").getTime();
//        long bEndTime = dateTime(YYYY_MM_DD_HH_MM_SS, "2023-03-22 15:50:00").getTime();
//        System.out.println(checkTimeOverlap(aStartTime, aEndTime, bStartTime, bEndTime, false));

//        System.out.println(computeTime(dateTime(YYYY_MM_DD_HH_MM_SS, "2023-03-21 08:50:00")));
        Date startTime = dateTime(YYYY_MM_DD, "2023-03-31");
        System.out.println(startTime);
    }
}
